﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using DynamicComparer;
using Shuba.Model;

namespace Shuba.Web.master
{
    public partial class branch_nip_so_list : basePage
    {
        string msg = "";
        bool IsView, IsAdd, IsEdit, IsDelete, IsChecker;
        int rowsPerPage = 20;
        string currentPage;
        int jmlRow;

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Form.DefaultFocus = txtSearch.ClientID;
            this.Form.DefaultButton = btnSearch.UniqueID;

            string acl = GetUserAccess("MSTR_BRANCH_NIP_SO_MAP");
            IsView = IsUserView(acl);
            IsAdd = IsUserAdd(acl);
            IsEdit = IsUserEdit(acl);
            IsDelete = IsUserDelete(acl);
            IsChecker = IsUserChecker(acl);

            if (!IsView)
            {
                msg = this.GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
            }

            if (!IsPostBack)
            {
                InitSort();
                ViewState["searchBy"] = "";
                currentPage = "1";
                ViewState["SortEx"] = "UPDATE_DATE";
                ViewState["Sort"] = "DESC";

                BindData();

                LabelTitle.Text = GetPageTitle("MSTR_BRANCH_NIP_SO_MAP");

                if (IsAdd)
                {
                    btnAdd.Enabled = true;
                    btnUpload.Enabled = true;
                }
                else
                {
                    btnAdd.Enabled = false;
                    btnUpload.Enabled = false;
                }
            }
        }

        private void BindData()
        {
            Shuba.Business.BranchNipSOMap BI = new Shuba.Business.BranchNipSOMap();
            List<BranchNipSOMapInfo> list;

            if (ddlPaging.Items.Count == 0 || ViewState["searchBy"].ToString() != txtSearch.Text)
                currentPage = "1";
            else currentPage = ddlPaging.SelectedValue;

            jmlRow = BI.GetRowListPaging(txtSearch.Text);

            list = BI.GetListPaging(txtSearch.Text, int.Parse(currentPage), gvList.PageSize);
            if (ViewState["SortEx"].ToString().Trim() != "")
            {
                string sort = sort = ViewState["SortEx"].ToString() + " " + ViewState["Sort"];
                DynamicComparer<BranchNipSOMapInfo> comparer = new DynamicComparer<BranchNipSOMapInfo>(sort);
                list.Sort(comparer);
            }
            gvList.DataSource = list;
            gvList.DataBind();
            load_data_page();

            if (IsDelete || IsEdit) gvList.Columns[gvList.Columns.Count - 1].Visible = true;
            else gvList.Columns[gvList.Columns.Count - 1].Visible = false;


            //FOR APPROVAL GRID
            if (IsChecker)
            {
                BindApprovalData();
                if (ApprovalGrid.Rows.Count > 0) { ApprovalPnl.Visible = true; } else { ApprovalPnl.Visible = false; }
            }
        }

        protected void load_data_page()
        {
            int jmlHal = (int)Math.Ceiling((decimal)jmlRow / (decimal)rowsPerPage);
            string pageNum;

            footLink.Visible = (jmlHal > 0);

            ddlPaging.Items.Clear();
            for (int i = 0; i < jmlHal; i++)
            {
                pageNum = (i + 1).ToString();
                ddlPaging.Items.Add(new ListItem(pageNum, pageNum));
            }

            if (ViewState["searchBy"].ToString() == txtSearch.Text)
                ddlPaging.SelectedValue = currentPage;
            ViewState["searchBy"] = txtSearch.Text;

            lblPage.Text = "Page " + currentPage + " of " + jmlHal;

            firstLink.Visible = true;
            prevLink.Visible = true;
            nextLink.Visible = true;
            lastLink.Visible = true;

            if (ddlPaging.SelectedIndex <= 0)
            {
                firstLink.Visible = false;
                prevLink.Visible = false;
            }
            if (ddlPaging.SelectedIndex >= ddlPaging.Items.Count - 1)
            {
                nextLink.Visible = false;
                lastLink.Visible = false;
            }
        }

        protected void linkDataPage_Click(object sender, EventArgs e)
        {
            if (sender == firstLink)
                ddlPaging.SelectedIndex = 0;
            else if (sender == prevLink)
                ddlPaging.SelectedIndex--;
            else if (sender == nextLink)
                ddlPaging.SelectedIndex++;
            else if (sender == lastLink)
                ddlPaging.SelectedIndex = ddlPaging.Items.Count - 1;
            BindData();
        }

        protected void ddlPaging_IndexChange(object sender, EventArgs e)
        {
            BindData();
        }

        protected void gvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvList.PageIndex = e.NewPageIndex;
            BindData();
        }

        protected void gvList_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortDirection(e.SortExpression, e.SortDirection.ToString());
            ViewState["SortEx"] = e.SortExpression;
            gvList.PageIndex = 0;
            BindData();
        }

        protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton btnDelete = (LinkButton)e.Row.FindControl("btnDelete");
                LinkButton btnEdit = (LinkButton)e.Row.FindControl("btnEdit");

                if (IsEdit) btnEdit.Enabled = true; else btnEdit.Enabled = false;

                if (IsDelete)
                {
                    btnDelete.Enabled = true;
                }
                else
                {
                    btnDelete.Enabled = false;
                    btnDelete.OnClientClick = "";
                }

                if (e.Row.RowIndex > 0)
                {
                    string prevBranchId = gvList.DataKeys[e.Row.RowIndex - 1].Value.ToString();
                    string BranchId = gvList.DataKeys[e.Row.RowIndex].Value.ToString();
                    if (prevBranchId == BranchId)
                    {
                        e.Row.Cells[0].Text = "";
                        e.Row.Cells[1].Text = "";
                    }
                }

                Label lblUserName = e.Row.FindControl("lblUserName") as Label;
                Label lblGroup = e.Row.FindControl("lblGroup") as Label;
                string UName = "", Group = "";
                string NIP = gvList.DataKeys[e.Row.RowIndex].Value == null ? "" : (string)gvList.DataKeys[e.Row.RowIndex].Value;

                Shuba.Business.User _user = new Shuba.Business.User();
                List<Shuba.Model.UserInfo> list;

                list = _user.GetUserGroupName(NIP);
                foreach (Shuba.Model.UserInfo item in list)
                {
                    UName = item.Name; 
                    Group += item.GroupId + " - " + item.GroupName + "<BR>";
                }
                lblUserName.Text = UName;//.Substring(0, UName.Length - 4);//if (AppN.Length > 0) AppN = AppN.Substring(0, AppN.Length - 4);
                lblGroup.Text = Group;
                //e.Row.Cells[2].Text = UName;
            }
        }

        protected void gvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Remove" || e.CommandName == "Edit")
            {
                //string[] ParamID = e.CommandArgument.ToString().Split('~');
                //string BranchID = ParamID[0].ToString().Trim();
                //string AOCode = ParamID[1].ToString().Trim();
                //string NIP = ParamID[2].ToString().Trim();

                string ParamID = e.CommandArgument.ToString();

                if (e.CommandName == "Remove")
                {
                    Shuba.Business.BranchNipSOMap BI = new Shuba.Business.BranchNipSOMap();
                    Shuba.Model.BranchNipSOMapInfo BIInfo = BI.Get(ParamID);

                    BIInfo.UPDATE_BY = HttpContext.Current.User.Identity.Name;
                    BIInfo.UPDATE_DATE = ProcessingDate();
                    BIInfo.ACT_TYPE = "DELETE";

                    try
                    {
                        BI.Save(BIInfo);
                        AddLog("DELETE", "DELETE BRANCH NIP SO MAPPING");
                    }
                    catch (Exception ex)
                    {
                        msg = ex.Message.ToString();
                        ErrBox.Visible = true;
                        ErrMsg.Text = msg;
                    }

                    if (msg == "") BindData();// RestartPage();
                }
                else
                {
                    Response.Redirect("branch_nip_so_add.aspx?a=ed&id=" + e.CommandArgument);
                }
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }

        /*======================================
               APPROVAL GRID START HERE
        =======================================
        */
        private void BindApprovalData()
        {
            Shuba.Business.BranchNipSOMap BI = new Shuba.Business.BranchNipSOMap();
            List<BranchNipSOMapInfo> list;

            string SPAWEBAppCode = ConfigurationManager.AppSettings["app.code"];
            string SPADAAppCode = ConfigurationManager.AppSettings["app.code.spada"];

            string AppCodeList = "'" + SPAWEBAppCode + "','" + SPADAAppCode + "'";

            list = BI.GetListApproval("", HttpContext.Current.User.Identity.Name, AppCodeList);
            if (ViewState["SortEx"].ToString().Trim() != "")
            {
                string sort = sort = ViewState["SortEx"].ToString() + " " + ViewState["Sort"];
                DynamicComparer<BranchNipSOMapInfo> comparer = new DynamicComparer<BranchNipSOMapInfo>(sort);
                list.Sort(comparer);
            }
            ApprovalGrid.DataSource = list;
            ApprovalGrid.DataBind();
        }

        protected void ApprovalGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            ApprovalGrid.PageIndex = e.NewPageIndex;
            BindApprovalData();
        }

        protected void ApprovalGrid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.Cells[2].Text.Trim() == "&nbsp;" || e.Row.Cells[5].Text.Trim() == "&nbsp;" || e.Row.Cells[6].Text.Trim() == "&nbsp;")
                {
                    e.Row.Font.Bold = true;
                    e.Row.ForeColor = System.Drawing.Color.Red;
                }
                else
                {
                    e.Row.Font.Bold = false;
                    e.Row.ForeColor = System.Drawing.Color.Black;
                }
            }
        }

        protected void ApprovalGrid_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortDirection(e.SortExpression, e.SortDirection.ToString());
            ViewState["SortEx"] = e.SortExpression;
            ApprovalGrid.PageIndex = 0;
            BindApprovalData();
        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            //bool IsValidData = false;
            int ErrorCount = 0, SuccessCount = 0;

            foreach (GridViewRow row in ApprovalGrid.Rows)
            {
                CheckBox chkItemSelect = (CheckBox)row.FindControl("chkItemSelect");
                if (chkItemSelect.Checked)
                {
                    if (row.ForeColor != System.Drawing.Color.Red)
                    {
                        //IsValidData = true;

                        string NIP = ApprovalGrid.DataKeys[row.RowIndex].Value.ToString();
                        string ActType = row.Cells[10].Text;

                        Approve(NIP, ActType, true);
                        SuccessCount++;
                    }
                    else
                    {
                        ErrorCount++;
                    }
                }
            }

            if (SuccessCount > 0 || ErrorCount > 0)
            {
                msg = "Approval Notification\\n\\nSuccessfully Approve : " + SuccessCount + " Record(s)\\n\\nFailed to Approve : " + ErrorCount + " Record(s)";
                if (ErrorCount > 0) msg += "\\n\\nPlease make sure:\\n- NIP is correct and already registered in Console Management \\n- Unit Code is correct";
                BindData();
                Alert(msg);
                //AlertAndRedirect(msg, Request.Url.PathAndQuery);
            }
            /*
            if (IsValidData)
            {
                msg = this.GetGlobalResourceObject("Messages", "ApproveAlert").ToString();
                BindData();
                Alert(msg);

                //AlertAndRedirect(msg, Request.Url.PathAndQuery);
            }
             */
        }

        protected void btnReject_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in ApprovalGrid.Rows)
            {
                CheckBox chkItemSelect = (CheckBox)row.FindControl("chkItemSelect");

                if (chkItemSelect.Checked)
                {
                    string NIP = ApprovalGrid.DataKeys[row.RowIndex].Value.ToString();
                    string ActType = row.Cells[8].Text;

                    Approve(NIP, ActType, false);
                }
            }
            msg = this.GetGlobalResourceObject("Messages", "NoApprove").ToString();
            BindData();
            Alert(msg);
            //AlertAndRedirect(msg, Request.Url.PathAndQuery);
        }
       
        private int Approve(string NIP, string ActType, bool IsApprove)
        {
            int status = 0;
            Shuba.Business.BranchNipSOMap BI = new Shuba.Business.BranchNipSOMap();

            if (IsApprove)
            {
                try
                {
                    status = BI.Approve(NIP, ActType, HttpContext.Current.User.Identity.Name, ProcessingDate());
                    AddLog("APPROVAL", "APPROVE BRANCH NIP SO MAPPING");
                }
                catch (Exception ex)
                {
                    ErrBox.Visible = true;
                    ErrMsg.Text = ex.Message;
                }
            }
            else
            {
                AddLog("APPROVAL", "REJECT BRANCH NIP SO MAPPING");
                status = BI.Reject(NIP);
            }
            return status;
        }

        protected void btnApproveAll_Click(object sender, EventArgs e)
        {
            int ErrorCount = 0, SuccessCount = 0;

            Shuba.Business.BranchNipSOMap BI = new Shuba.Business.BranchNipSOMap();
            List<BranchNipSOMapInfo> list;

            string SPAWEBAppCode = ConfigurationManager.AppSettings["app.code"];
            string SPADAAppCode = ConfigurationManager.AppSettings["app.code.spada"];

            string AppCodeList = "'" + SPAWEBAppCode + "','" + SPADAAppCode + "'";

            list = BI.GetListApproval("", HttpContext.Current.User.Identity.Name, AppCodeList);

            foreach (BranchNipSOMapInfo item in list)
            {
                try
                {
                    if (Approve(item.NIP, item.ACT_TYPE, true) > 0)
                    {
                        SuccessCount++;
                    }
                    else ErrorCount++;

                }
                catch (Exception)
                {
                    ErrorCount++;
                }                
            }
            if (SuccessCount > 0 || ErrorCount > 0)
            {
                msg = "Approval Notification\\n\\nTotal record to approve : " + list.Count + " Record(s)\\nSuccessfully Approve : " + SuccessCount + " Record(s)\\nFailed to Approve : " + ErrorCount + " Record(s)";
                if (ErrorCount > 0) msg += "\\n\\nPlease make sure:\\n- NIP is correct and already registered in Console Management \\n- Unit Code is correct";
            }
            BindData();
            Alert(msg);
        }

        protected void btnRejectAll_Click(object sender, EventArgs e)
        {
            int ErrorCount = 0, SuccessCount = 0;

            Shuba.Business.BranchNipSOMap BI = new Shuba.Business.BranchNipSOMap();
            List<BranchNipSOMapInfo> list;

            string SPAWEBAppCode = ConfigurationManager.AppSettings["app.code"];
            string SPADAAppCode = ConfigurationManager.AppSettings["app.code.spada"];

            string AppCodeList = "'" + SPAWEBAppCode + "','" + SPADAAppCode + "'";

            list = BI.GetListApproval("", HttpContext.Current.User.Identity.Name, AppCodeList);

            foreach (BranchNipSOMapInfo item in list)
            {
                try
                {
                    if (Approve(item.NIP, item.ACT_TYPE, false) > 0)
                    {
                        SuccessCount++;
                    }
                    else ErrorCount++;
                }
                catch (Exception)
                {
                    ErrorCount++;
                }
            }
            if (SuccessCount > 0 || ErrorCount > 0)
            {
                msg = "Approval Notification\\n\\nTotal record to reject : " + list.Count + " Record(s)\\nSuccessfully Reject : " + SuccessCount + " Record(s)\\nFailed to Reject : " + ErrorCount + " Record(s)";
            }
            BindData();
            Alert(msg);
        }
    }
}
